let express = require('express');
let { pool } = require("../config/mysql_config");
let router = express.Router();
const fs = require("fs"); // 读写文件的模块
const formidable = require('formidable');//处理大文件上传的文件信息；
let { query, upload_info } = require('../dao/user/user_dao');

router.get('/', function (req, res, next) { // users 相关接口说明文档页面
  res.render('user', {
    title: 'usersApi',
    apiList: [
      {
        url: "users/adduser(添加用户)",
        method: "POST",
        params: {
          headerImg: "用户头像",
          username: "用户名称",
          addres: "用户地址",
          sex: "用户性别",
          mobile: "手机号",
          email: "邮箱"
        },
        result: {
          "success": true,
          "data": ``
        }
      },
      {
        url: "users/deleteuser(删除用户)",
        method: "GET",
        params: {
          id: "用户ID"
        },
        result: {
          "success": true,
          "data": ``
        }
      },
      {
        url: "users/deleteuser(查询用户)",
        method: "GET",
        params: {
          id: "用户ID"
        },
        result: {
          "success": true,
          "data": `{
                        id: 1,
                        headerImg:"用户头像", 
                        username:"用户名称",
                        addres:"用户地址",
                        sex:"用户性别",
                        mobile:"手机号",
                        email:"邮箱"
                    }`
        }
      },
    ]
  });;
});

// 上传头像
router.post('/upload_avatar', function (req, res, next) {
  let form = new formidable.IncomingForm();
  form.uploadDir = './upload/image';
  form.parse(req, function (err, fields, files) {
    if (err) {
      res.json({ "result": '-1', "msg": '保存失败' })
      return
    }
    console.log(files)
    let oldpath = files[fields.filename].path;
    let newpath = `${oldpath}.${files[fields.filename].name.split('.')[1]}`;
    fs.rename(oldpath, newpath, (err) => {
      //改变上传文件的存放位置和文件名
      if (err) {
        res.json({ "result": '-2', "msg": '保存失败' })
        return
      }
      res.json({ "result": '1', "msg": '保存成功', avatar_path: newpath })
    })
  });
  form.on('error', function (err) {
    console.log('upload error:', err)
    res.json({ "result": '-3', "msg": '保存失败' })
  });

})
/* 添加用户 */
router.post('/adduser', function (req, res, next) {
  let params = req.query;
  params.skills = JSON.stringify(params.skills)
  req.query.vip = req.query.vip === 'true' ? true : false
  let sqlparam = [params.username, params.sex, params.create_times, params.vip, params.skills, params.is_stu, params.introduce];
  let sql = 'INSERT INTO user (username, sex, create_times, vip, skills, is_stu, introduce) VALUES (?, ?, ?, ?, ?, ?, ?);';
  pool.query(sql, sqlparam, function (err, rows) {
    if (err) {
      throw err;
    } else {
      console.log(rows);
      if (rows.insertId !== 0) {
        res.json({
          code: 20000,
          message: '添加成功'
        });
      } else {
        res.json({
          code: 20001,
          message: '添加失败'
        });
      }
    }
  });
})

// 登录
router.post('/login', function (req, res, next) {
  let params = req.body;
  let sqlparam = [params.username];
  let sql = 'SELECT password from user where username = ?;'
  let resObj;
  pool.query(sql, sqlparam, function (err, rows) {
    if (err) {
      throw err;
    } else {
      if (rows.length > 0) {
        if (params.password === rows[0].password) {
          resObj = {
            code: 20000,
            message: '账号正确',
            data: {
              token: params.username
            }
          }
        } else {
          resObj = {
            code: 20002,
            message: '账号或密码错误'
          }
        }
      } else {
        resObj = {
          code: 20001,
          message: '用户不存在'
        }
      }
      res.json(resObj);
    }
  })
})

// 获取信息
router.get('/info', function (req, res, next) {
  let params = req.query;
  let sqlparam = [params.token];
  let sql = 'SELECT username,introduce,avatar,roles from user where username = ?;'
  let resObj;
  pool.query(sql, sqlparam, function (err, rows) {
    if (err) {
      throw err;
    } else {
      if (rows.length > 0) {
        resObj = {
          code: 20000,
          message: 'success',
          data: rows[0]
        }
      } else {
        resObj = {
          code: 20001,
          message: 'token验证失败'
        }
      }
      res.json(resObj);
    }
  })
})

// 退出登录
router.post('/logout', function (req, res, next) {
  //  清除服务器缓存 未做
  // let params = req.body;
  let resObj;
  resObj = {
    code: 20000,
    message: 'success'
  }
  res.json(resObj);
})

// 获取指定用户信息 get请求
router.get('/queryuser', function (req, res, next) {
  // let urlParam = {
  //   id: req.query.id
  // };
  // console.log(urlParam);
  query({}, function (success) {
    // let r =  result.createResult(true, success);
    res.json(success);
  })
});



module.exports = router;
